package com.yeban.bams.client.clientsocket;

import com.yeban.bams.server.serversocket.RequestTO;
import com.yeban.bams.server.serversocket.ResponseTO;

import javax.swing.*;
import java.awt.*;
import java.util.function.Consumer;

/**
 * @Desc 客户端请求工具类
 * 封装：构造请求对象 -> 发送请求 -> 统一处理反馈
 * @Author yeban
 * @Date 2025/11/7
 */
public class RequestHelper {

    private ClientRequest clientRequest;

    public RequestHelper(ClientRequest clientRequest) {
        this.clientRequest = clientRequest;
    }

    public static ResponseTO sendRequest(RequestTO request) {
        return ClientRequest.send(request);
    }

    public static ResponseTO sendRequest(Component parent, RequestTO request, String title) {
        return ClientRequest.send(request);
    }

    public static void sendRequestAsync(Component parent, RequestTO request, String title, Consumer<ResponseTO> callback) {
        new SwingWorker<ResponseTO, Void>(){
            @Override protected ResponseTO doInBackground() { return ClientRequest.send(request); }
            @Override protected void done() {
                try {
                    ResponseTO resp = get();
                    int type = resp.isSuccess() ? JOptionPane.INFORMATION_MESSAGE : JOptionPane.ERROR_MESSAGE;
                    JOptionPane.showMessageDialog(parent, resp.getMessage(), title, type);
                    if (callback != null) callback.accept(resp);
                } catch (Exception ex) {
                    ResponseTO fail = new ResponseTO(false, null, "请求失败：" + ex.getMessage());
                    JOptionPane.showMessageDialog(parent, fail.getMessage(), title, JOptionPane.ERROR_MESSAGE);
                    if (callback != null) callback.accept(fail);
                }
            }
        }.execute();
    }
}
